/**
 * Project:   dtu.fmes.googleloon
 * File:      KillRandomBalloonSimulationLink.java
 * License: 
 *            This file is licensed under GNU General Public License version 3
 *            http://www.gnu.org/licenses/gpl-3.0.txt
 *
 * Copyright:	Nicolai Sonne [ NicolaiSonne@hotmail.com.com ]
 * Date:      Dec 11, 2013
 */

package dtu.fmes.loon.simulation.processors;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import dtu.fmes.loon.model.Balloon;
import dtu.fmes.loon.model.KillRandomBalloon;

/**
 * Kills random balloon if specified
 * 
 * @author Nicolai Sonne
 * 
 */
public class KillRandomBalloonSimulationLink extends SimulationLink {

	@Override
	public void run() {
		// Check if random balloon killing have been set
		if (css.getSimulation().getKillRandomBalloons() != null && !css.getSimulation().getKillRandomBalloons().isEmpty()) {
			// Initialize random generator
			Random rand = new Random(Double.doubleToLongBits(Math.random()));

			// Iterate through random balloon specifiers
			for (KillRandomBalloon krb : css.getSimulation().getKillRandomBalloons()) {
				// If command have reached its time constraint and haven't been
				// executed: EXECUTE IT!
				if (!krb.isExecuted() && krb.getTime() <= css.getSimulation().getCurrentTime()) {
					List<Balloon> allBalloons = css.getBalloons();
					List<Balloon> aliveBalloons = new ArrayList<Balloon>();

					// Find alive balloons
					for (Balloon balloon : allBalloons) {
						boolean withinX = true;
						boolean withinY = true;

						// If area constraints have been specified: adhere to
						// them
						if (krb.getxStart() != null && krb.getxStop() != null && krb.getyStart() != null && krb.getyStop() != null) {
							withinX = balloon.getLatitude() >= krb.getxStart() && balloon.getLatitude() <= krb.getxStop();
							withinY = balloon.getLongitude() >= krb.getyStart() && balloon.getLongitude() <= krb.getyStop();
						}

						if (balloon.isAlive() && balloon.isCanBeRevived() && withinX && withinY) aliveBalloons.add(balloon);
					}

					if (!aliveBalloons.isEmpty()) {
						// Chose random balloon and kill it

						Balloon markedForDeath = aliveBalloons.get(rand.nextInt(aliveBalloons.size()));

						markedForDeath.setAlive(false);
						markedForDeath.setCanBeRevived(false);
						markedForDeath.setOptimalPos(null);
						markedForDeath.setTargetPosition(null);
						markedForDeath.setTargetAltitude(null);

						// Mark command executed, so it won't be executed again
						krb.setExecuted(true);
					}
				}
			}
		}
	}

}
